<?php
/**
 * Created by PhpStorm.
 * User: gyq
 * Date: 2018/11/6
 * Time: 20:37
 */

namespace app\api\service;


use app\lib\enum\ScopeEnum;
use app\lib\exception\ForbiddenException;
use app\lib\exception\TokenException;
use think\Exception;
use think\facade\Cache;
use think\facade\Request;

class Token
{
    public static function generateToken()
    {
//        32个字符组成一组随机字符串
//        总共三组
//        随机字符串
//        时间戳
//        盐，放入config中
        $randChars = getRandChars(32);
        $timestamp = $_SERVER['REQUEST_TIME'];
        $salt = config('secure.salt');

        return md5($randChars . $timestamp . $salt);
    }

    public static function getCurrentTokenVar($key)
    {
        $token = Request::instance()->header('token');
        $vars = Cache::get($token);
        if (!$vars) {
            throw new TokenException();
        } else {
            if (!is_array($vars)) {
                $vars = json_decode($vars, true);
            }
            if (array_key_exists($key, $vars)) {
                return $vars[$key];
            } else {
                throw new Exception('尝试获取的Token变量不存在');
            }
        }
    }

    public static function getTokenScope()
    {
        return self::getCurrentTokenVar('scope');
    }

    public static function getTokenUid()
    {
        return self::getCurrentTokenVar('uid');
    }

    public static function needPrimaryScope()
    {
        $scope = self::getTokenScope();
        if ($scope) {
            if ($scope >= ScopeEnum::User) {
                return true;
            } else {
                throw new ForbiddenException();
            }
        } else {
            throw new TokenException();
        }
    }

    public static function needExclusiveScope()
    {
        $scope = self::getTokenScope();
        if ($scope) {
            if ($scope == ScopeEnum::User) {
                return true;
            } else {
                throw new ForbiddenException();
            }
        } else {
            throw new TokenException();
        }
    }

    public static function isValidOperate($checkUID)
    {
        if (!$checkUID) {
            throw new Exception('检查UID时必须传入一个被检查的UID');
        }
        if (self::getTokenUid() != $checkUID) {
            return false;
        }
        return true;
    }
}